<template>
  <!-- // 地图 -->
  <div class="homePageCards1">
    <div id="warrmap998" style="width: 100%; height: 100%"></div>
    <div class="full-box" @click="goBack">
      <img :src="imgUrl2" alt="" />
      <span>返回</span>
    </div>
  </div>
</template>
<script>
import sjccKey from "@/config/sjmapkey";

export default {
  name: "ResourceMap",
  props: {
    mapCenter: {
      type: Array,
      default: () => [113.95751054215168, 30.93002374011205]
    },
    mapZoom: {
      type: Number,
      default: 8
    }
  },
  data() {
    return {
      map: null, // 基础地图
      timer: null,
      imgUrl2: require("@/assets/img/nofull.png"),
      carMarker: null,
      // 轨迹回放的线路数据
      lineFeature: {
        geometry: {
          type: "LineString",
          coordinates: [
            [113.95437986573688, 30.932089472199095],
            [113.95954032136564, 30.932797712927055],
            [113.9604348003424, 30.92834161101844],
            [113.95523994167456, 30.927662848794455],
            [113.95486150826173, 30.929876186112494],
            [113.95751054215168, 30.93002374011205]
          ]
        },
        properties: {},
        type: "Feature"
      },
      // 经过插值后的线路数据
      chunkData: null
    };
  },
  beforeDestroy() {
    this.map && this.map.remove();
    this.map = null;
    if (this.timer) {
      clearInterval(this.timer);
    }

  },
  mounted() {
    this.initLocalMap();
  },
  methods: {
    goBack() {
      this.$emit("closeMap");
    },
    initLocalMap() {
      SGMap.tokenTask.login(sjccKey.appkey, sjccKey.appsecret).then((res) => {
        this.map = new SGMap.Map({
          // 地图绑定的DOM元素ID
          container: "warrmap998",
          // 地图样式
          style: "aegis://styles/aegis/Streets",
          // 默认缩放层级
          zoom: 16,
          // 地图中心点
          center: this.mapCenter,
          // 地图默认字体
          localIdeographFontFamily: "Microsoft YoHei"
        });

        this.map.on("load", (e) => {
          const url = require("@/assets/map/renwu.png");
          this.map.loadImage(url, (error, image) => {
            // 添加图片到map，可以设置图片id
            // 添加轨迹回放的路线图层，已走过和未走过的
            this.addRouterLayer();
            // 创建小车
            this.createCar();
            // 对线路进行插值处理，返回插值后的路径数据
            this.joinLinePoint();
            // 开始路径回放操作
            this.startReplaying();
          }
          );
        });
      });
    },
    addRouterLayer() {
      // 已经走过的路线图层
      this.map.addLayer({
        id: "route-played",
        type: "line",
        source: {
          type: "geojson",
          data: {
            type: "FeatureCollection",
            features: []
          }
        },
        layout: {
          "line-join": "round",
          "line-cap": "round"
        },
        paint: {
          "line-color": "#4dc86f",
          "line-width": 4
        }
      });
    },

    createCar() {
      // 画marker点
      var el = document.createElement("div");
      el.className = "marker car-marker";
      this.carMarker = new SGMap.Marker(el).setLngLat(this.lineFeature.geometry.coordinates[0]).addTo(this.map);
    },
    /* global turf */
    joinLinePoint() {
      // 回放时车辆速度，单位公里/每小时
      // 播放速度，这里选择20倍播放速度
      const replaySpeed = 20;
      // 按照实际车辆跑的速度，每秒跑 60 / 3600 km
      // 车辆位置按每秒刷新20帧算，1/20秒移动的距离为 60 / 3600 / 20 km
      const step = 60 / 3600 / 20;
      // 倍数播放时，每帧移动的步长为 step * replaySpeed
      const scaleSpeed = step * replaySpeed;
      // 线路根据步长scaleSpeed间隔进行插值，插值线总长/步长(distance/scaleSpeed)个点，得到chunkData
      // 注意：线路长度一定，scaleSpeed越小，插值数量越多。线路长度很长的情况下，请调整replaySpeed，避免插值点数过多产生卡顿
      this.chunkData = turf.lineChunk(
        this.lineFeature,
        scaleSpeed,
        {
          units: "kilometers"
        }
      );

      // 非必须，地图上展示经过插值处理后的线路点
      this.map.addLayer({
        id: "demo",
        type: "circle",
        source: {
          type: "geojson",
          data: {
            type: "FeatureCollection",
            features: this.chunkData.features.reduce((total, cell) => {
              total.push({
                type: "Feature",
                geometry: {
                  type: "Point",
                  coordinates: cell.geometry.coordinates[0]
                }
              });
              return total;
            }, [])
          }
        },
        paint: {
          "circle-radius": 2,
          "circle-color": "red"
        }
      });
    },

    startReplaying() {
      const features = this.chunkData.features;

      const max = features.length;
      let order = 0;

      this.timer = setInterval(() => {
        order++;
        if (order >= max) {
          clearInterval(this.timer);
        } else {
          // const beforePoint = features[order - 1].geometry.coordinates[1];
          const nowPoint = features[order].geometry.coordinates[1];
          // 设置小车的位置
          this.carMarker.setLngLat(nowPoint);
          // 设置小车的方向
          // var bearing = turf.bearing(
          //   turf.point(beforePoint),
          //   turf.point(nowPoint)
          // );
          // bearing && this.carMarker.setRotation(bearing - 90);
          // 更新已走过的线路图层数据
          this.readerReplayedRouterLayer(order);
        }
      }, 1000 / 20); // 间隔1000 / 20执行一次，每秒执行20次，可以和上面计算线路的时间间隔配合
    },
    readerReplayedRouterLayer(order) {
      this.map.getSource("route-played").setData({
        type: "FeatureCollection",
        features: this.chunkData.features.slice(0, order + 1)
      });
    }
  }
};
</script>

<style scoped lang="less">
.homePageCards1 {
  position: relative;
  width: 100%;
  height: 100%;
  box-sizing: border-box;
  padding: 6px;
  border-radius: 5px;

  #map {
    border-radius: 5px;
  }
}

.full-box {
  position: absolute;
  top: 10px;
  right: 10px;
  display: flex;
  align-items: center;
  font-size: 18px;
  font-weight: 700;
  z-index: 9;
  background-color: #fff;
  cursor: pointer;
  padding: 3px 8px;
  border-radius: 5px;

  img {
    width: 15px;
    height: 15px;
    margin-right: 5px;
  }
}

:deep(.sgmap-popup-content) {
  background-color: #46577c !important;
  padding: 0 !important;
}
</style>
